<?php

namespace Admin\Controller;

use Common\Controller\BaseController;

/**
 * App用户管理
 */
class MemberController extends BaseController {

    /**
     * 用户列表
     */
    public function memberList() {
        $pageSize = I('post.pageSize', C('PAGE_SIZE'));
        $pageCurrent = I('post.pageCurrent', 1);
        $orderField = I('post.orderField', 'u.id');
        $orderDirection = I('post.orderDirection', 'DESC');

        $name = I('post.name', '');
        $phone = I('post.phone', '');

        //参数数组
        $params = array();
        //构造WHERE条件
        $where = '1=1 ';
        if (!empty($name)) {
            $params['name'] = $name;
            $where .= "AND u.name LIKE '%{$name}%' ";
        }
        if (!empty($phone)) {
            $params['phone'] = $phone;
            $where .= "AND u.phone LIKE '%{$phone}%' ";
        }

        $users = M('Users');
        //数据总数
        $total = $users->alias('u')->where($where)->count();

        //数据列表
        $list = $users->alias('u')
                ->join('__USER_GROUP_ACCESS__ uga ON u.id = uga.user_id')
                ->where($where)
                ->field('u.*,uga.status as ustatus,uga.group_id')
                ->order("{$orderField} {$orderDirection}")
                ->page("{$pageCurrent},{$pageSize}")
                ->select();

        if (!empty($list)) {
            $commonStatus = C('COMMON_STATUS');
            //用户级别,构造数组
            $userGroup = M('UserGroup')->where("status=1")->select();
            $ug = array();
            if (!empty($userGroup)) {
                foreach ($userGroup as $v) {
                    $ug[$v['id']] = $v['name'];
                }
            }
            foreach ($list as &$item) {
                $item['reg_time'] = $item['reg_time'] ? date('Y-m-d H:i:s', intval($item['reg_time'])) : '';

                $item['group_name'] = array_key_exists($item['group_id'], $ug) ? $ug[$item['group_id']] : '';
                $item['status_name'] = array_key_exists($item['status'], $commonStatus) ? $commonStatus[$item['status']] : '';
            }
        }

        $this->assign('pageSize', $pageSize);
        $this->assign('pageCurrent', $pageCurrent);
        $this->assign('orderField', $orderField);
        $this->assign('orderDirection', $orderDirection);
        $this->assign('total', $total);
        $this->assign('list', $list);
        $this->assign('params', $params);
        $this->display();
    }

    /**
     * 添加用户
     */
    public function addMember() {
        if (IS_POST) {
            $phone = I('post.phone', '');
            $name = I('post.name', '');
            $password = I('post.password', '');
            $remark = I('post.remark', '');
            $group_id = I('post.group_id', 0);
            $status = I('post.status', 1);

            $users = M('Users');
            $userGroupAccess = M('UserGroupAccess');

            if (empty($phone)) {
                ajaxReturn('手机号不能为空', 300);
            }
            if (empty($name)) {
                ajaxReturn('用户名不能为空', 300);
            }
            if (empty($group_id)) {
                ajaxReturn('账号级别不能为空', 300);
            }
            if (empty($password)) {
                ajaxReturn('用户密码不能为空', 300);
            }
            if (mb_strlen($password) < 6) {
                ajaxReturn('用户密码最少6位', 300);
            }
            $existName = $users->where("name='{$name}'")->find();
            if (!empty($existName)) {
                ajaxReturn('该用户名已经存在', 300);
            }

            $data = $users->create();
            if ($data) {
                $data['status'] = $status;
                $data['password'] = md5($data['password']);
                $data['reg_time'] = time();
                $data['upd_time'] = time();
                $data['reg_ip'] = get_client_ip();

                $ret = $users->add($data);
                if ($ret) {
                    if (!empty($group_id)) {
                        $userGroupAccess->add(array('user_id' => $ret, 'group_id' => $group_id));
                    }

                    ajaxReturn('添加用户成功', 200, '', '', '', 'Admin/Member/memberList');
                } else {
                    ajaxReturn('添加用户失败', 300);
                }
            } else {
                ajaxReturn('创建数据对象失败', 300);
            }
        } else {
            $commonStatus = C('COMMON_STATUS');

            $userGroup = M('UserGroup')->where("status=1")->select();

            $this->assign('commonStatus', $commonStatus);
            $this->assign('userGroup', $userGroup);
            $this->display();
        }
    }

    /**
     * 删除用户
     */
    public function delMember() {
        $ids = I('get.ids', '');

        if (empty($ids)) {
            ajaxReturn('请选择删除项', 300);
        }
        $users = M('Users');
        $userGroupAccess = M('UserGroupAccess');

        $users->startTrans();
        $ret1 = $users->where("FIND_IN_SET(id,'{$ids}')")->delete();
        $ret2 = $userGroupAccess->where("FIND_IN_SET(user_id,'{$ids}')")->delete();

        if ($ret1 && $ret2) {//操作成功
            // 提交事务
            $users->commit();
            ajaxReturn('删除成功', 200, '', '', '', 'Admin/Member/memberList');
        } else {
            // 事务回滚
            $users->rollback();
            ajaxReturn('删除失败', 300);
        }
    }

    /**
     * 修改用户
     */
    public function updMember() {
        if (IS_POST) {
            $userId = I('post.userId', '');
            $phone = I('post.phone', '');
            $name = I('post.name', '');
            $password = I('post.password', '');
            $remark = I('post.remark', '');
            $group_id = I('post.group_id', 0);
            $status = I('post.status', 1);

            $users = M('Users');
            $userGroupAccess = M('UserGroupAccess');

            if (empty($userId)) {
                ajaxReturn('用户ID不能为空', 300);
            }
            if (empty($phone)) {
                ajaxReturn('手机号不能为空', 300);
            }
            if (empty($name)) {
                ajaxReturn('姓名不能为空', 300);
            }
            $userInfo = $users->where("id={$userId}")->find();
            if (empty($userInfo)) {
                ajaxReturn('没有找到该用户信息', 300);
            }

            $existPhone = $users->where("phone='{$phone}' AND id!={$userId}")->find();
            if (!empty($existPhone)) {
                ajaxReturn('该手机号已经存在', 300);
            }

            $data = $users->create();
            if ($data) {
                $data['status'] = $status;
                $data['upd_time'] = time();

                if (!empty($password)) {
                    $data['password'] = md5($password);
                } else {
                    unset($data['password']);
                }
                $ret = $users->where("id={$userId}")->save($data);
                if ($ret) {
                    //先删除，后添加
                    $userGroupAccess->where("user_id={$userId}")->delete();
                    if (!empty($group_id)) {
                        $userGroupAccess->add(array('user_id' => $userId, 'group_id' => $group_id));
                    }

                    ajaxReturn('修改用户成功', 200, '', '', '', 'Admin/Member/memberList');
                } else {
                    ajaxReturn('修改用户失败', 300);
                }
            } else {
                ajaxReturn('创建数据对象失败', 300);
            }
        } else {
            $userId = I('get.userId', '');

            if (empty($userId)) {
                ajaxReturn('用户ID不能为空', 300);
            }

            $userInfo = M('Users')->alias('u')
                    ->join('__USER_GROUP_ACCESS__ uga ON u.id=uga.user_id')
                    ->where("u.id={$userId}")
                    ->field('u.*,uga.group_id')
                    ->find();
                    
            if (empty($userInfo)) {
                ajaxReturn('没有找到该用户信息', 300);
            }

            $commonStatus = C('COMMON_STATUS');
            //获取用户组信息
            $userGroup = M('UserGroup')->where("status=1")->select();

            $this->assign('commonStatus', $commonStatus);
            $this->assign('userGroup', $userGroup);
            $this->assign('userInfo', $userInfo);
            $this->display();
        }
    }

}
